﻿import { Injectable } from '@angular/core';
import {
    CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot,
    CanActivateChild, NavigationExtras, CanLoad, Route
} from '@angular/router';

import { AppServiceMembership } from './app.service.membership';

@Injectable()
export class AppServiceAuthGuard implements CanActivate, CanActivateChild, CanLoad {
    constructor(private appServiceMembership: AppServiceMembership, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        return this.checkLogin(url);
    }

    canLoad(route: Route): boolean {
        let url = `/${route.path}`;
        return this.checkLogin(url);
    }
    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
    }

    checkLogin(url: string): boolean {
        if (this.appServiceMembership.isLoggedIn) {
            return true;
        }
        //store the attempted URL for redirecting
        this.appServiceMembership.redirectUrl = url;
        //create a dummy session id
        let sessionId = 1234567890;

        let navigationExtras: NavigationExtras = {
            queryParams: { 'session_id': sessionId }
        };

        this.router.navigate(['/login'], navigationExtras);
        return false;
    }
}